import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerMessageHandler extends SimpleChannelInboundHandler<IMessage> {


    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static Map<String, Channel> channelMap = new ConcurrentHashMap<>(16);
    private MessageResolverFactory resolverFactory = MessageResolverFactory.getInstance();


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, IMessage iMessage) throws Exception {
        Resolver resolver = resolverFactory.getMessageResolver(iMessage);
        IMessage result = resolver.resolver(iMessage, ctx);
        ctx.writeAndFlush(result);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        AttributeKey<String> attributeKey = AttributeKey.valueOf("username");
        String username = ctx.channel().attr(attributeKey).get();
        channelMap.remove(username);
        System.out.println(username + "登出成功！");
    }
}
